package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.FollowBehaviorDto;
import com.heima.behavior.pojos.ApFollowBehavior;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Gareth Cao
 * @date 2022/6/24 12:06
 */
@Service
public class ApFollowBehaviorServiceImpl implements ApFollowBehaviorService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult follow(FollowBehaviorDto dto) {
        //1 校验参数是否存在
        if (dto.getAuthorId() == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2 从本地线程获取用户信息
        ApUser apUser = ApThreadLocalUtil.getUser();
        if (apUser == null) {
            //未登录或者登录过期了
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (apUser.getId() == 0) {
            //游客不让进行用户行为操作
            return ResponseResult.errorResult(AppHttpCodeEnum.VISITOR_NEED_LOGIN);
        }

        //3 TODO 判断进行关注与否
        //定义关注的大key，大key为用户id，小key为用户关注的作者id
        String follow_key = "USER_FOLLOW_" + apUser.getId();
        //定义粉丝的大key，大key为作者id，小key为该作者被关注的用户id
        String fans_key = "USER_FANS_" + dto.getAuthorId();
        //查询redis中是否存在以hash类型所存的key,第一个为大key，第二个小key，都必须用字符串，否则会序列化为乱码
        Boolean followFlag = stringRedisTemplate.opsForHash().hasKey(follow_key, dto.getAuthorId() + "");
        //3.1 用户已经关注了作者，此时还要关注operation=0，直接返回
        if (followFlag && dto.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FOLLOW_USER_END_SUCCESS);
        }
        //3.2 用户已经关注了作者，此时要取消关注operation=1
        if (followFlag && dto.getOperation() == 1) {
            //要清空缓存和mongoDB的数据
            //3.2.1 清空redis缓存
            stringRedisTemplate.opsForHash().delete(follow_key, dto.getAuthorId() + "");
            stringRedisTemplate.opsForHash().delete(fans_key, apUser.getId());
            //3.2.1 清空mongoDB中用户id和作者id匹配的数据
            Query query = Query.query(Criteria.where("userId").is(apUser.getId())
                    .and("followId").is(dto.getAuthorId()));
            mongoTemplate.remove(query, ApFollowBehavior.class);
        }
        //3.3 用户没有关注作者，此时操作关注operation=0
        if (!followFlag && dto.getOperation() == 0) {
            //3.3.1 redis中需要新增key
            stringRedisTemplate.opsForHash().put(follow_key, dto.getAuthorId() + "", "1");
            stringRedisTemplate.opsForHash().put(fans_key, apUser.getId() + "", "1");
            //3.3.2 mongoDB新增数据
            ApFollowBehavior apFollowBehavior = new ApFollowBehavior();
            apFollowBehavior.setId(ObjectId.get().toHexString());
            apFollowBehavior.setUserId(apUser.getId().longValue());
            apFollowBehavior.setArticleId(dto.getArticleId());
            apFollowBehavior.setFollowId(dto.getAuthorId());
            apFollowBehavior.setCreatedTime(new Date());
            mongoTemplate.insert(apFollowBehavior);
        }
        return ResponseResult.okResult("关注成功");
    }
}
